package com.ruoyi.web.controller.workJob;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.ruoyi.common.constant.AttendanceConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.poi.ExcelHandleUtil;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.worker.domain.*;
import com.ruoyi.worker.service.AttendanceStatisticsService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 月度考勤汇总
 *
 * @param
 * @author 刘松山
 * @date 2021/10/8 16:49
 * @return null
 */

@RestController
@RequestMapping("/workJobApi/monthlyAttendance")
public class AttendanceStatisticsController extends BaseController {
    private static final Logger LOGGER = LoggerFactory.getLogger(AttendanceStatisticsController.class);
    @Autowired
    private AttendanceStatisticsService attendanceStatisticsService;

    /**
     * 通过导入记录excel计算月度考勤
     *
     * @param file
     * @return com.ruoyi.common.core.domain.AjaxResult
     * @author 刘松山
     * @date 2021/10/8 16:49
     */
    // @PreAuthorize("@ss.hasPermi('job:monthlyAttendance:calculateAttendance')")
    @PostMapping("/calculateAttendance")
    public AjaxResult calculateAttendance(MultipartFile file) {
        List<MonthlyAttendanceIni> iniList = new ArrayList<>();
        try {
            iniList = baseImport(file.getInputStream(), 0, 1, false, MonthlyAttendanceIni.class);
        } catch (Exception e) {
            LOGGER.error("员工通行记录导入失败:[{}]", e.getMessage(), e);
        }
        if (null == iniList) {
            return AjaxResult.error("excel员工通行记录导入失败，信息为空");
        }
        //获取所有用户列表

        List<List<MonthlyAttendanceIni>> userOfList = Lists.newArrayList();
        iniList.stream().collect(Collectors.groupingBy(MonthlyAttendanceIni::getUserCode, Collectors.toList()))
                .forEach((userCode, userList) -> {
                    userOfList.add(userList);
                });

        String[] dates = DateUtils.getDates("2021", "10");
        List<MonthlyAttendanceResult> resultList = new ArrayList<>();

        for (List<MonthlyAttendanceIni> list : userOfList) {
            MonthlyAttendanceResult monthlyAttendanceResult = new MonthlyAttendanceResult();
            int data1 = 0;
            int data2 = 0;
            int data3 = 0;
            //早退
            int dataEarly = 0;
            //旷工
            int dataDefect = 0;
            //异常汇总
            int dataAbnormalSum = 0;
//            //实际出勤
//            int dataActual = 0;
            //出勤汇总
            int dataActualSum = 0;

            List<Integer> intList = new ArrayList<>();
            for (int i = 0; i < dates.length; i++) {
                int k = 0;
                //实际出勤
                int dataActual = 0;
                int morning = 0;
                int noon = 0;
                int night = 0;
                //是否异常
                int dataAbnormal = 0;
                Date dateMorning1 = DateUtils.dateTime("yyyy-MM-dd HH:mm", dates[i] + " 08:30");
                Date dateMorning2 = DateUtils.dateTime("yyyy-MM-dd HH:mm", dates[i] + " 08:45");
                Date dateMorning3 = DateUtils.dateTime("yyyy-MM-dd HH:mm", dates[i] + " 09:00");
                Date dateMorning4 = DateUtils.dateTime("yyyy-MM-dd HH:mm", dates[i] + " 09:30");
                Date dateMorning5 = DateUtils.dateTime("yyyy-MM-dd HH:mm", dates[i] + " 12:00");
                Date dateMorning6 = DateUtils.dateTime("yyyy-MM-dd HH:mm", dates[i] + " 12:30");

                Date dateNoon1 = DateUtils.dateTime("yyyy-MM-dd HH:mm", dates[i] + " 13:30");
                Date dateNoon2 = DateUtils.dateTime("yyyy-MM-dd HH:mm", dates[i] + " 13:45");
                Date dateNoon3 = DateUtils.dateTime("yyyy-MM-dd HH:mm", dates[i] + " 14:00");
                Date dateNoon4 = DateUtils.dateTime("yyyy-MM-dd HH:mm", dates[i] + " 14:30");
                Date dateNoon5 = DateUtils.dateTime("yyyy-MM-dd HH:mm", dates[i] + " 18:00");
                Date dateNoon6 = DateUtils.dateTime("yyyy-MM-dd HH:mm", dates[i] + " 18:30");

                Date dateNight1 = DateUtils.dateTime("yyyy-MM-dd HH:mm", dates[i] + " 19:30");
                Date dateNight2 = DateUtils.dateTime("yyyy-MM-dd HH:mm", dates[i] + " 19:45");
                Date dateNight3 = DateUtils.dateTime("yyyy-MM-dd HH:mm", dates[i] + " 20:00");
                Date dateNight4 = DateUtils.dateTime("yyyy-MM-dd HH:mm", dates[i] + " 20:30");
                Date dateNight5 = DateUtils.dateTime("yyyy-MM-dd HH:mm", DateUtils.getDifferDay(DateUtils.dateTime("yyyy-MM-dd", dates[i]), 1) + " 08:00");
                Date dateNight6 = DateUtils.dateTime("yyyy-MM-dd HH:mm", DateUtils.getDifferDay(DateUtils.dateTime("yyyy-MM-dd", dates[i]), 1) + " 08:30");

                for (MonthlyAttendanceIni m : list) {
                    Date dateTime = DateUtils.dateTime("yyyy-MM-dd HH:mm", m.getDateTime());
                    String date = DateUtils.parseStrToStr("yyyy-MM-dd", m.getDateTime());
                    monthlyAttendanceResult.setUserName(m.getUserName());
                    monthlyAttendanceResult.setUserCode(m.getUserCode());
                    if (date.equals(dates[i])) {
                        k++;
                        dataActual = 1;
                        if (dateMorning1.getTime() >= dateTime.getTime()) {
                            morning = 1;

                        } else if (dateMorning1.getTime() <= dateTime.getTime() && dateMorning2.getTime() > dateTime.getTime()) {
                            if (morning != 1) {
                                data1 = data1 + 1;
                                dataAbnormal = 1;
                            }
                            morning = 1;

                        } else if (dateMorning2.getTime() <= dateTime.getTime() && dateMorning3.getTime() > dateTime.getTime()) {
                            if (morning != 1) {
                                data2 = data2 + 1;
                                dataAbnormal = 1;
                            }
                            morning = 1;

                        } else if (dateMorning3.getTime() < dateTime.getTime() && dateMorning4.getTime() >= dateTime.getTime()) {
                            if (morning != 1) {
                                data3 = data3 + 1;
                                dataAbnormal = 1;
                            }
                            morning = 1;

                        } else if (dateMorning4.getTime() < dateTime.getTime() && dateMorning5.getTime() >= dateTime.getTime()) {
                            if (morning != 1) {
                                dataDefect = dataDefect + 1;
                                dataAbnormal = 1;
                            }
                            morning = 1;

                        }

                        if (dateMorning5.getTime() <= dateTime.getTime() && dateMorning6.getTime() > dateTime.getTime()) {
                            dataEarly = dataEarly + 1;
                            dataAbnormal = 1;

                        }


                        if (dateNoon1.getTime() >= dateTime.getTime()) {
                            noon = 1;

                        } else if (dateNoon1.getTime() <= dateTime.getTime() && dateNoon2.getTime() > dateTime.getTime()) {
                            if (noon != 1) {
                                data1 = data1 + 1;
                                dataAbnormal = 1;
                            }
                            noon = 1;

                        } else if (dateNoon2.getTime() <= dateTime.getTime() && dateNoon3.getTime() > dateTime.getTime()) {
                            if (noon != 1) {
                                data2 = data2 + 1;
                                dataAbnormal = 1;
                            }
                            noon = 1;

                        } else if (dateNoon3.getTime() < dateTime.getTime() && dateNoon4.getTime() >= dateTime.getTime()) {
                            if (noon != 1) {
                                data3 = data3 + 1;
                            }
                            noon = 1;

                        } else if (dateNoon4.getTime() < dateTime.getTime() && dateNoon5.getTime() >= dateTime.getTime()) {
                            if (noon != 1) {
                                dataDefect = dataDefect + 1;
                                dataAbnormal = 1;
                            }
                            noon = 1;

                        }

                        if (dateNoon5.getTime() <= dateTime.getTime() && dateNoon6.getTime() > dateTime.getTime()) {
                            dataEarly = dataEarly + 1;
                            dataAbnormal = 1;

                        }


                        if (dateNight1.getTime() >= dateTime.getTime()) {
                            night = 1;

                        } else if (dateNight1.getTime() <= dateTime.getTime() && dateNight2.getTime() > dateTime.getTime()) {
                            if (night != 1) {
                                data1 = data1 + 1;
                                dataAbnormal = 1;
                            }
                            night = 1;

                        } else if (dateNight2.getTime() <= dateTime.getTime() && dateNight3.getTime() > dateTime.getTime()) {
                            if (night != 1) {
                                data2 = data2 + 1;
                                dataAbnormal = 1;
                            }
                            night = 1;

                        } else if (dateNight3.getTime() < dateTime.getTime() && dateNight4.getTime() >= dateTime.getTime()) {
                            if (night != 1) {
                                data3 = data3 + 1;
                            }
                            night = 1;

                        } else if (dateNight4.getTime() < dateTime.getTime() && dateNight5.getTime() >= dateTime.getTime()) {
                            if (night != 1) {
                                dataDefect = dataDefect + 1;
                                dataAbnormal = 1;
                            }
                            night = 1;

                        }

                        if (dateNight5.getTime() <= dateTime.getTime() && dateNight6.getTime() > dateTime.getTime()) {
                            dataEarly = dataEarly + 1;
                            night = 1;
                            dataAbnormal = 1;

                        }

                    }

                }
                intList.add(k);
                dataAbnormalSum = dataAbnormalSum + dataAbnormal;
                dataActualSum = dataActualSum + dataActual;
            }

            monthlyAttendanceResult.setData1(data1);
            monthlyAttendanceResult.setData2(data2);
            monthlyAttendanceResult.setData3(data3);
            monthlyAttendanceResult.setDataEarly(dataEarly);
            monthlyAttendanceResult.setDataActual(0);
            monthlyAttendanceResult.setDataAbnormal(dataAbnormalSum);
            monthlyAttendanceResult.setDataActual(dataActualSum);
            if (intList.size() > 1) {
                monthlyAttendanceResult.setDate1(intList.get(0));
            }
            if (intList.size() > 2) {
                monthlyAttendanceResult.setDate2(intList.get(1));
            }
            if (intList.size() > 3) {
                monthlyAttendanceResult.setDate3(intList.get(2));
            }
            if (intList.size() > 4) {
                monthlyAttendanceResult.setDate4(intList.get(3));
            }
            if (intList.size() > 5) {
                monthlyAttendanceResult.setDate5(intList.get(4));
            }
            if (intList.size() > 6) {
                monthlyAttendanceResult.setDate6(intList.get(5));
            }
            if (intList.size() > 7) {
                monthlyAttendanceResult.setDate7(intList.get(6));
            }
            if (intList.size() > 8) {
                monthlyAttendanceResult.setDate8(intList.get(7));
            }
            if (intList.size() > 9) {
                monthlyAttendanceResult.setDate9(intList.get(8));
            }
            if (intList.size() > 10) {
                monthlyAttendanceResult.setDate10(intList.get(9));
            }
            if (intList.size() > 11) {
                monthlyAttendanceResult.setDate11(intList.get(10));
            }
            if (intList.size() > 12) {
                monthlyAttendanceResult.setDate12(intList.get(11));
            }
            if (intList.size() > 13) {
                monthlyAttendanceResult.setDate13(intList.get(12));
            }
            if (intList.size() > 14) {
                monthlyAttendanceResult.setDate14(intList.get(13));
            }
            if (intList.size() > 15) {
                monthlyAttendanceResult.setDate15(intList.get(14));
            }
            if (intList.size() > 16) {
                monthlyAttendanceResult.setDate16(intList.get(15));
            }
            if (intList.size() > 17) {
                monthlyAttendanceResult.setDate17(intList.get(16));
            }
            if (intList.size() > 18) {
                monthlyAttendanceResult.setDate18(intList.get(17));
            }
            if (intList.size() > 19) {
                monthlyAttendanceResult.setDate19(intList.get(18));
            }
            if (intList.size() > 20) {
                monthlyAttendanceResult.setDate20(intList.get(19));
            }
            if (intList.size() > 21) {
                monthlyAttendanceResult.setDate21(intList.get(20));
            }
            if (intList.size() > 22) {
                monthlyAttendanceResult.setDate22(intList.get(21));
            }
            if (intList.size() > 23) {
                monthlyAttendanceResult.setDate23(intList.get(22));
            }
            if (intList.size() > 24) {
                monthlyAttendanceResult.setDate24(intList.get(23));
            }
            if (intList.size() > 25) {
                monthlyAttendanceResult.setDate25(intList.get(24));
            }
            if (intList.size() > 25) {
                monthlyAttendanceResult.setDate26(intList.get(25));
            }
            if (intList.size() > 27) {
                monthlyAttendanceResult.setDate27(intList.get(26));
            }
            if (intList.size() > 28) {
                monthlyAttendanceResult.setDate28(intList.get(27));
            }
            if (intList.size() > 29) {
                monthlyAttendanceResult.setDate29(intList.get(28));
            }
            if (intList.size() > 30) {
                monthlyAttendanceResult.setDate30(intList.get(29));
            }

            resultList.add(monthlyAttendanceResult);
        }

        for (MonthlyAttendanceIni m : iniList) {
            m.setDate(DateUtils.parseStrToStr("yyyy-MM-dd", m.getDateTime()));
        }

        List<List<MonthlyAttendanceIni>> dateOfList = Lists.newArrayList();
        iniList.stream().collect(Collectors.groupingBy(MonthlyAttendanceIni::getDate, Collectors.toList()))
                .forEach((date, dateList) -> {
                    dateOfList.add(dateList);
                });
        List<List<MonthlyAttendanceIni>> dateResultList = Lists.newArrayList();
        for (List<MonthlyAttendanceIni> list : dateOfList) {
            List<MonthlyAttendanceIni> lst = list.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(
                            () -> new TreeSet<>(Comparator.comparing(o -> o.getUserCode()))),
                    ArrayList::new));
            dateResultList.add(lst);
        }

        MonthlyAttendanceResult monthlyAttendanceResult = new MonthlyAttendanceResult();
        monthlyAttendanceResult.setUserName("统计：");
        if (dateResultList.size() > 1) {
            monthlyAttendanceResult.setDate1(dateResultList.get(0).size());
        }
        if (dateResultList.size() > 2) {
            monthlyAttendanceResult.setDate2(dateResultList.get(1).size());
        }
        if (dateResultList.size() > 3) {
            monthlyAttendanceResult.setDate3(dateResultList.get(2).size());
        }
        if (dateResultList.size() > 4) {
            monthlyAttendanceResult.setDate4(dateResultList.get(3).size());
        }
        if (dateResultList.size() > 5) {
            monthlyAttendanceResult.setDate5(dateResultList.get(4).size());
        }
        if (dateResultList.size() > 6) {
            monthlyAttendanceResult.setDate6(dateResultList.get(5).size());
        }
        if (dateResultList.size() > 7) {
            monthlyAttendanceResult.setDate7(dateResultList.get(6).size());
        }
        if (dateResultList.size() > 8) {
            monthlyAttendanceResult.setDate8(dateResultList.get(7).size());
        }
        if (dateResultList.size() > 9) {
            monthlyAttendanceResult.setDate9(dateResultList.get(8).size());
        }
        if (dateResultList.size() > 10) {
            monthlyAttendanceResult.setDate10(dateResultList.get(9).size());
        }
        if (dateResultList.size() > 11) {
            monthlyAttendanceResult.setDate11(dateResultList.get(10).size());
        }
        if (dateResultList.size() > 12) {
            monthlyAttendanceResult.setDate12(dateResultList.get(11).size());
        }
        if (dateResultList.size() > 13) {
            monthlyAttendanceResult.setDate13(dateResultList.get(12).size());
        }
        if (dateResultList.size() > 14) {
            monthlyAttendanceResult.setDate14(dateResultList.get(13).size());
        }
        if (dateResultList.size() > 15) {
            monthlyAttendanceResult.setDate15(dateResultList.get(14).size());
        }
        if (dateResultList.size() > 16) {
            monthlyAttendanceResult.setDate16(dateResultList.get(15).size());
        }
        if (dateResultList.size() > 17) {
            monthlyAttendanceResult.setDate17(dateResultList.get(16).size());
        }
        if (dateResultList.size() > 18) {
            monthlyAttendanceResult.setDate18(dateResultList.get(17).size());
        }
        if (dateResultList.size() > 19) {
            monthlyAttendanceResult.setDate19(dateResultList.get(18).size());
        }
        if (dateResultList.size() > 20) {
            monthlyAttendanceResult.setDate20(dateResultList.get(19).size());
        }
        if (dateResultList.size() > 21) {
            monthlyAttendanceResult.setDate21(dateResultList.get(20).size());
        }
        if (dateResultList.size() > 22) {
            monthlyAttendanceResult.setDate22(dateResultList.get(21).size());
        }
        if (dateResultList.size() > 23) {
            monthlyAttendanceResult.setDate23(dateResultList.get(22).size());
        }
        if (dateResultList.size() > 24) {
            monthlyAttendanceResult.setDate24(dateResultList.get(23).size());
        }
        if (dateResultList.size() > 25) {
            monthlyAttendanceResult.setDate25(dateResultList.get(24).size());
        }
        if (dateResultList.size() > 26) {
            monthlyAttendanceResult.setDate26(dateResultList.get(25).size());
        }
        if (dateResultList.size() > 27) {
            monthlyAttendanceResult.setDate27(dateResultList.get(26).size());
        }
        if (dateResultList.size() > 28) {
            monthlyAttendanceResult.setDate28(dateResultList.get(27).size());
        }
        if (dateResultList.size() > 29) {
            monthlyAttendanceResult.setDate29(dateResultList.get(28).size());
        }
        if (dateResultList.size() > 30) {
            monthlyAttendanceResult.setDate30(dateResultList.get(29).size());
        }

        resultList.add(monthlyAttendanceResult);
        if (resultList.isEmpty()) {
            return AjaxResult.error("需要导出的数据为空");
        }
        ExcelUtil<MonthlyAttendanceResult> util = new ExcelUtil<MonthlyAttendanceResult>(MonthlyAttendanceResult.class);
        AjaxResult a = util.exportExcel(resultList, "月度考勤数据");

        return a;
    }


    // @PreAuthorize("@ss.hasPermi('job:attendanceGroup:list')")
    @GetMapping("/listUserDayAttendanceSum")
    public TableDataInfo listUserDayAttendanceSum(UserDayAttendanceSum userDayAttendanceSum) {
        startPage();
        List<UserDayAttendanceSum> list = attendanceStatisticsService.listUserDayAttendanceSum(userDayAttendanceSum);
        return getDataTable(list);
    }

    // @PreAuthorize("@ss.hasPermi('job:attendanceGroup:detail:export')")
    @GetMapping("/userDayAttendanceSumExport")
    public AjaxResult userDayAttendanceSumExport(UserDayAttendanceSum userDayAttendanceSum) {
        List<UserDayAttendanceSum> list = attendanceStatisticsService.listUserDayAttendanceSum(userDayAttendanceSum);
        if (list.isEmpty()) {
            return AjaxResult.error("需要导出的数据为空");
        }

        ExcelUtil<UserDayAttendanceSum> util = new ExcelUtil<UserDayAttendanceSum>(UserDayAttendanceSum.class);
        return util.exportExcel(list, "每日考勤汇总");

    }


    /**
     * 每日考勤明细查询
     * @author 刘松山
     * @date 2021/10/27 16:57
     * @param userDayAttendance
     * @return com.ruoyi.common.core.page.TableDataInfo
     */
    // @PreAuthorize("@ss.hasPermi('job:attendanceGroup:list')")
    @GetMapping("/listUserDayAttendance")
    public TableDataInfo listUserDayAttendance(UserDayAttendance userDayAttendance) {
        startPage();
        List<UserDayAttendance> list = attendanceStatisticsService.listUserDayAttendance(userDayAttendance);
        return getDataTable(list);
    }
    /**
     * 每日考勤明细导出
     * @author 刘松山
     * @date 2021/10/27 16:58
     * @param userDayAttendance
     * @return com.ruoyi.common.core.domain.AjaxResult
     */
    // @PreAuthorize("@ss.hasPermi('job:attendanceGroup:detail:export')")
    @GetMapping("/userDayAttendanceExport")
    public AjaxResult userDayAttendanceExport(UserDayAttendance userDayAttendance) {
        List<UserDayAttendance> list = attendanceStatisticsService.listUserDayAttendance(userDayAttendance);
        if (list.isEmpty()) {
            return AjaxResult.error("需要导出的数据为空");
        }

        ExcelUtil<UserDayAttendance> util = new ExcelUtil<UserDayAttendance>(UserDayAttendance.class);
        return util.exportExcel(list, "每日考勤明细");

    }
     /**
      * 获取当天所在月份第一日 到当前日
      * @author 刘松山
      * @date 2021/10/27 16:58
      * @return com.ruoyi.common.core.page.TableDataInfo
      */
    @GetMapping("/getDateArray/{date}")
    public TableDataInfo getDateArray(@PathVariable(value = "date", required = false) String date) {
        int month = 0;
        String currentDate = DateUtils.getDate();
        long  currentDateValue =Long.parseLong(currentDate.substring(0,7).replaceAll("-",""));
        if(currentDateValue>Long.parseLong(date.replaceAll("-",""))){
            month =Integer.parseInt(date.substring(5, 7));
            currentDate=DateUtils.getLastDayOfMonth(month);
        }else{
            month =Integer.parseInt(currentDate.substring(5, 7));
        }


        String firstDay = DateUtils.getFirstDayOfMonth(month);
        List<String> dateArray = null;
        try {
            dateArray = DateUtils.findDates(firstDay, currentDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return getDataTable(dateArray);
    }
    /**
     * 每月考勤汇总查询
     * @author 刘松山
     * @date 2021/10/27 16:59
     * @param userMonthAttendanceSum
     * @return com.ruoyi.common.core.page.TableDataInfo
     */
    // @PreAuthorize("@ss.hasPermi('job:attendanceGroup:list')")
    @GetMapping("/listUserMonthAttendanceSum")
    public TableDataInfo listUserMonthAttendanceSum(UserMonthAttendanceSum userMonthAttendanceSum) {
        startPage();
        List<UserMonthAttendanceSum> list = attendanceStatisticsService.listUserMonthAttendanceSum(userMonthAttendanceSum);
        return getDataTable(list);
    }
     /**
      * 每月考勤汇总导出 未做
      * @author 刘松山
      * @date 2021/10/27 17:00
      * @param userMonthAttendanceSum
      * @return com.ruoyi.common.core.domain.AjaxResult
      */
    // @PreAuthorize("@ss.hasPermi('job:attendanceGroup:detail:export')")
    @GetMapping("/userMonthAttendanceSumExport")
    public AjaxResult userMonthAttendanceSumExport(UserMonthAttendanceSum userMonthAttendanceSum) {
        List<UserMonthAttendanceSum> list = attendanceStatisticsService.listUserMonthAttendanceSum(userMonthAttendanceSum);
        if (list.isEmpty()) {
            return AjaxResult.error("需要导出的数据为空");
        }

        ExcelUtil<UserMonthAttendanceSum> util = new ExcelUtil<UserMonthAttendanceSum>(UserMonthAttendanceSum.class);
        return util.exportExcel(list, "每月考勤明细");

    }
    /**
     * 每月考勤明细列表查询
     * @author 刘松山
     * @date 2021/10/27 17:00
     * @param userMonthAttendance
     * @return com.ruoyi.common.core.page.TableDataInfo
     */
    // @PreAuthorize("@ss.hasPermi('job:attendanceGroup:list')")
    @GetMapping("/listUserMonthAttendance")
    public TableDataInfo listUserMonthAttendance(UserMonthAttendance userMonthAttendance) {
        startPage();
        List<UserMonthAttendance> list = attendanceStatisticsService.listUserMonthAttendance(userMonthAttendance);
        return getDataTable(list);
    }

    /**
     * 每月考勤汇总明细列表导出
     * @author 刘松山
     * @date 2021/10/27 17:00
     * @param userMonthAttendance
     * @param request
     * @param response
     * @return com.ruoyi.common.core.domain.AjaxResult
     */
    // @PreAuthorize("@ss.hasPermi('job:attendanceGroup:detail:export')")
    @GetMapping("/userMonthAttendanceExport")
    public AjaxResult userMonthAttendanceExport(UserMonthAttendance userMonthAttendance, HttpServletRequest request, HttpServletResponse response) {
        List<UserMonthAttendance> list = attendanceStatisticsService.listUserMonthAttendance(userMonthAttendance);
        if (list.isEmpty()) {
            return AjaxResult.error("需要导出的数据为空");
        }

        List<Map<String, Object>> resultlist = new ArrayList<>();
        for (UserMonthAttendance u : list) {
            Map<String, Object> map = new HashMap<>();
            map.put("userName", u.getUserName());
            map.put("idCard", u.getIdCard());
            map.put("isCome", u.getIsCome());
            map.put("isAttendance", u.getIsAttendance());
            map.put("late", u.getLate());
            map.put("generallyLate", u.getGenerallyLate());
            map.put("seriouslyLate", u.getSeriouslyLate());
            map.put("leaveEarly", u.getLeaveEarly());
            map.put("absenteeism", u.getAbsenteeism());
            for (int i = 0; i < u.getDataList().size(); i++) {
                map.put(u.getDataList().get(i).get("dateTime").toString(), u.getDataList().get(i).get("type"));
            }
            resultlist.add(map);
        }

        OutputStream output = null;
        try {

            List<String> titleList = new ArrayList<>();
            List<String> filedNames = new ArrayList<>();
            titleList.add("姓名");
            titleList.add("身份证");

            titleList.add("岗位");
            titleList.add("应出勤天数");
            titleList.add("实际出勤天数");
            titleList.add("异常天数");
            titleList.add("本月严重迟到天数");
            titleList.add("本月早退次数");
            titleList.add("本月旷工次数");

            filedNames.add("userName");
            filedNames.add("idCard");

            filedNames.add("isCome");
            filedNames.add("isAttendance");
            filedNames.add("late");
            filedNames.add("generallyLate");
            filedNames.add("seriouslyLate");
            filedNames.add("leaveEarly");
            filedNames.add("absenteeism");

            String currentDate = DateUtils.getDate();
            int month = Integer.parseInt(currentDate.substring(5, 7));
            String firstDay = DateUtils.getFirstDayOfMonth(month);
            List<String> dateArray = null;
            try {
                dateArray = DateUtils.findDates(firstDay, currentDate);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            for (int i = 0; i < dateArray.size(); i++) {

                titleList.add(dateArray.get(i));
                filedNames.add(dateArray.get(i));
            }
//            List<String> titleList = Arrays.asList(title);
//            List<String> filedNames = Arrays.asList(name);
            output = response.getOutputStream();
            response.reset();
            response.setHeader("Content-disposition", "attachment; filename=" + System.currentTimeMillis() + "_monthAttendance.xls");
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            HSSFWorkbook workbook = ExcelHandleUtil.exportExcel(titleList, resultlist, filedNames);
            workbook.write(output);
            return AjaxResult.success("导出成功，请查看");
        } catch (Exception e) {
            logger.debug("导出失败：" + e.getMessage());
            return AjaxResult.error("导出失败");
        } finally {
            if (output != null) {
                try {
                    output.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
    // @PreAuthorize("@ss.hasPermi('job:monthlyAttendance:calculateAttendance')")
    @PostMapping("/dayAttendanceImport")
    public AjaxResult dayAttendanceImport(MultipartFile file) {
        List<MonthlyAttendanceIni> iniList = new ArrayList<>();
        try {
            //导入日考勤数据
            iniList = baseImport(file.getInputStream(), 0, 1, false, MonthlyAttendanceIni.class);
        } catch (Exception e) {
            LOGGER.error("员工通行记录导入失败:[{}]", e.getMessage(), e);
        }
        if (null == iniList) {
            return AjaxResult.error("excel员工通行记录导入失败，信息为空");
        }
        List<String> hadNotDatetimeList = new ArrayList<>();
        for (MonthlyAttendanceIni m : iniList) {
            if (m.getDateTime() == null || m.getDateTime().equals("")) {
                hadNotDatetimeList.add("excel员工通行记录中" + m.getUserName() + "通行时间为空");
            }

        }
        if (hadNotDatetimeList.size() > 0) {
            return AjaxResult.error(hadNotDatetimeList.toString());
        }
        MonthlyAttendanceIni fistRecord = iniList.get(0);
        String fistRecordDateTime = fistRecord.getDateTime();
        String date = DateUtils.parseStrToStr("yyyy-MM-dd", fistRecordDateTime);
        //excel同名字信息集合
        Set<String> userSet = new HashSet<>();
        for (MonthlyAttendanceIni m : iniList) {
            if (DateUtils.parseStrToStr("yyyy-MM-dd", m.getDateTime()).equals(date)) {
                userSet.add(m.getUserName());
            }
        }
        Map<String, Object> paraMap = new HashMap<>();
        paraMap.put("dateTime", fistRecordDateTime);
        paraMap.put("list", userSet);
        //用户信息？？？
        List<Map<String, Object>> groupList = attendanceStatisticsService.listGroupByUserName(paraMap);
        //已排班信息表
        List<UserDayAttendance> scheduleList = attendanceStatisticsService.listUserScheduleInfo(paraMap);

        if (scheduleList.size() < 1) {
            return AjaxResult.error(date + "没有排班信息，请核对！".toString());
        }

        //获取考勤组下数据列表  班次/用户名称
        List<List<UserDayAttendance>> groupOfList = Lists.newArrayList();
        scheduleList.stream().collect(Collectors.groupingBy(UserDayAttendance::getGroupId, Collectors.toList()))
                .forEach((groupId, templist) -> {
                    groupOfList.add(templist);
                });

        //导入数据以用户身份证分组
        List<List<MonthlyAttendanceIni>> userOfList = Lists.newArrayList();
        iniList.stream().collect(Collectors.groupingBy(MonthlyAttendanceIni::getUserCode, Collectors.toList()))
                .forEach((userCode, templist) -> {
                    userOfList.add(templist);
                });
        //获取当天所有用户的排班记录列表
        List<Map<String, Object>> userScheduleList = attendanceStatisticsService.listUserSchedule(fistRecordDateTime);
        Date dateTime = DateUtils.dateTime("yyyy-MM-dd HH:mm", fistRecordDateTime);
        String baseDate = DateUtils.parseStrToStr("yyyy-MM-dd", fistRecordDateTime);
        List<UserDayAttendance> resultList = new ArrayList<>();
        Map<String, Object> resultMap = new HashMap<>();

        Date date1 = null;
        Date date2 = null;
        Date date3 = null;
        Date date4 = null;
        Date date5 = null;
        Date date6 = null;
        Date date7 = null;
        Date date8 = null;

        //应该出勤的人数
        int mustCome = 0;

        //排班表信息 与 导入excel考勤信息以名称比对 比对成功放入 collectList 中 userList 中存放通勤记录
        List<Map<String, Object>> restList = new ArrayList<>();
        List<Map<String, Object>> tempRestList = new ArrayList<>();
        List<Map<String, Object>> collectList = new ArrayList<>();
        for (int i = 0; i < userScheduleList.size(); i++) {
            Map<String, Object> map = userScheduleList.get(i);
            String userName = map.get("userName").toString();
            int flag =0;
            for (List<MonthlyAttendanceIni> l : userOfList) {
                if (userName.equals(l.get(0).getUserName())) {
                    map.put("userList", l);
                    collectList.add(map);
                    flag =1;
                  break;
                }
            }
            //排班了但是没有考勤记录的 后续判断为旷工
            if(flag ==0){
                List<MonthlyAttendanceIni> l = new ArrayList<>();
                map.put("userList", l);
                collectList.add(map);
            }


            //顺序不可调
            if (null != map.get("name") && "休息".equals(map.get("name").toString())) {
                Map<String,Object> resMap = Maps.newHashMap();
                resMap.put(map.get("groupId").toString(),map);
                restList.add(resMap);
                continue;
            }
        }

        //循环合并后的列表 对比落入通行记录里 有 正常  没有 异常
        for (int i = 0; i < collectList.size(); i++) {
            Map<String, Object> map = collectList.get(i);
            List<MonthlyAttendanceIni> l = (List<MonthlyAttendanceIni>) collectList.get(i).get("userList");
            Map<String, Object> restMap = null;
            if ("休息".equals(map.get("name").toString())) {
//                //不知道先循环去重
//                for (Map<String, Object> stringObjectMap : restList) {
//                    if (!stringObjectMap.containsKey(map.get("groupId").toString())) {
//                        restMap = new HashMap<>();
//                        restMap.put(map.get("groupId").toString(), map);
//                        tempRestList.add(restMap);
//                    }
//                }
                UserDayAttendance userDayAttendance = new UserDayAttendance();
                userDayAttendance.setIsAttendance(0);
                userDayAttendance.setUserId(Long.parseLong(map.get("userId").toString()));
                userDayAttendance.setUserName(map.get("userName").toString());
                userDayAttendance.setGroupId(Long.parseLong(map.get("groupId").toString()));
                userDayAttendance.setIsCome(0);
                userDayAttendance.setIsAbnormal(0);
                userDayAttendance.setCreateBy(getUsername());
                userDayAttendance.setPostId(Long.parseLong(map.get("postId").toString()));
                userDayAttendance.setPostName(map.get("postName").toString());
                userDayAttendance.setDateTime(DateUtils.parseDateToStr("yyyy-MM-dd", dateTime));
                if(l.size()>0){
                    userDayAttendance.setIdCard(l.get(0).getIdCard());
                }
                resultList.add(userDayAttendance);
                continue;
            }
            mustCome++;
            //一个长期工一天一条记录
            UserDayAttendance userDayAttendance = new UserDayAttendance();
            userDayAttendance.setGroupId(Long.parseLong(map.get("groupId").toString()));
            userDayAttendance.setUserId(Long.parseLong(map.get("userId").toString()));
            userDayAttendance.setUserName(map.get("userName").toString());
            if(l.size()>0){
                userDayAttendance.setIdCard(l.get(0).getIdCard());
            }

            userDayAttendance.setCreateBy(getUsername());
            userDayAttendance.setPostId(Long.parseLong(map.get("postId").toString()));
            userDayAttendance.setPostName(map.get("postName").toString());
            userDayAttendance.setIsAbnormal(0);
            userDayAttendance.setDateTime(DateUtils.parseDateToStr("yyyy-MM-dd", dateTime));
            userDayAttendance.setIsAttendance(1);
            userDayAttendance.setIsCome(1);
            int type = Integer.parseInt(map.get("type").toString());

            userDayAttendance.setMustNum(type * 2);
            if (Integer.parseInt(map.get("firstBeginChecked").toString()) == 0) {
                date1 = DateUtils.dateTime("yyyy-MM-dd HH:mm", baseDate + " " + map.get("firstBeginTime"));
            } else {
                date1 = DateUtils.dateTime("yyyy-MM-dd HH:mm", DateUtils.getDifferDay(DateUtils.dateTime("yyyy-MM-dd", baseDate), 1) + " " + map.get("firstBeginTime"));
            }
            if (Integer.parseInt(map.get("firstEndChecked").toString()) == 0) {
                date2 = DateUtils.dateTime("yyyy-MM-dd HH:mm", baseDate + " " + map.get("firstEndTime"));
            } else {
                date2 = DateUtils.dateTime("yyyy-MM-dd HH:mm", DateUtils.getDifferDay(DateUtils.dateTime("yyyy-MM-dd", baseDate), 1) + " " + map.get("firstEndTime"));
            }

            if (type > 1) {
                if (Integer.parseInt(map.get("secondBeginChecked").toString()) == 0) {
                    date3 = DateUtils.dateTime("yyyy-MM-dd HH:mm", baseDate + " " + map.get("secondBeginTime"));
                } else {
                    date3 = DateUtils.dateTime("yyyy-MM-dd HH:mm", DateUtils.getDifferDay(DateUtils.dateTime("yyyy-MM-dd", baseDate), 1) + " " + map.get("secondBeginTime"));
                }
                if (Integer.parseInt(map.get("secondEndChecked").toString()) == 0) {
                    date4 = DateUtils.dateTime("yyyy-MM-dd HH:mm", baseDate + " " + map.get("secondEndTime"));
                } else {
                    date4 = DateUtils.dateTime("yyyy-MM-dd HH:mm", DateUtils.getDifferDay(DateUtils.dateTime("yyyy-MM-dd", baseDate), 1) + " " + map.get("secondEndTime"));
                }


            }
            if (type > 2) {
                if (Integer.parseInt(map.get("threeBeginChecked").toString()) == 0) {
                    date5 = DateUtils.dateTime("yyyy-MM-dd HH:mm", baseDate + " " + map.get("threeBeginTime"));
                } else {
                    date5 = DateUtils.dateTime("yyyy-MM-dd HH:mm", DateUtils.getDifferDay(DateUtils.dateTime("yyyy-MM-dd", baseDate), 1) + " " + map.get("threeBeginTime"));
                }
                if (Integer.parseInt(map.get("threeEndChecked").toString()) == 0) {
                    date6 = DateUtils.dateTime("yyyy-MM-dd HH:mm", baseDate + " " + map.get("threeEndTime"));
                } else {
                    date6 = DateUtils.dateTime("yyyy-MM-dd HH:mm", DateUtils.getDifferDay(DateUtils.dateTime("yyyy-MM-dd", baseDate), 1) + " " + map.get("threeEndTime"));
                }


            }
            if (type > 3) {
                if (Integer.parseInt(map.get("fourBeginChecked").toString()) == 0) {
                    date7 = DateUtils.dateTime("yyyy-MM-dd HH:mm", baseDate + " " + map.get("fourBeginTime"));
                } else {
                    date7 = DateUtils.dateTime("yyyy-MM-dd HH:mm", DateUtils.getDifferDay(DateUtils.dateTime("yyyy-MM-dd", baseDate), 1) + " " + map.get("fourBeginTime"));
                }
                if (Integer.parseInt(map.get("fourEndChecked").toString()) == 0) {
                    date8 = DateUtils.dateTime("yyyy-MM-dd HH:mm", baseDate + " " + map.get("fourEndTime"));
                } else {
                    date8 = DateUtils.dateTime("yyyy-MM-dd HH:mm", DateUtils.getDifferDay(DateUtils.dateTime("yyyy-MM-dd", baseDate), 1) + " " + map.get("fourEndTime"));
                }

            }

            int flag = 0;
            //长期工通行记录
            for (MonthlyAttendanceIni m : l) {
                //第一次上班正常打卡情况
                if (AttendanceConstants.addressIn.indexOf(m.getAddress()) != -1) {
                    if (DateUtils.dateTime("yyyy-MM-dd HH:mm", m.getDateTime()).getTime() >= date1.getTime() - AttendanceConstants.beforeDateTime
                            && DateUtils.dateTime("yyyy-MM-dd HH:mm", m.getDateTime()).getTime() <= date1.getTime()) {
                        userDayAttendance.setIsAttendance(1);
                        userDayAttendance.setIsCome(1);
                        userDayAttendance.setNormalNum(1 + userDayAttendance.getNormalNum());
                        userDayAttendance.setFirstStatus("正常");
                        userDayAttendance.setFirstBeginTime(m.getDateTime());
                        flag = 1;
                        break;
                    }

                }
            }
            if (flag == 0) {
                //上班异常处理
                userDayAttendance = this.inWork(userDayAttendance, l, map, date1);
                userDayAttendance.setFirstStatus("异常");
                userDayAttendance.setFirstBeginTime(userDayAttendance.getSaveTime());
                if (userDayAttendance.getAbsenteeism() > 0) {
                    userDayAttendance.setAbsenteeism1(1);
                    userDayAttendance.setAbsenteeism(0);
                }

            }

            flag = 0;
            for (MonthlyAttendanceIni m : l) {
                //第一次下班打卡情况
                if (AttendanceConstants.addressOut.indexOf(m.getAddress()) != -1) {
                    if (DateUtils.dateTime("yyyy-MM-dd HH:mm", m.getDateTime()).getTime() >= date2.getTime()
                            && DateUtils.dateTime("yyyy-MM-dd HH:mm", m.getDateTime()).getTime() <= date2.getTime() + AttendanceConstants.afterDateTime
                    ) {
                        userDayAttendance.setIsAttendance(1);
                        userDayAttendance.setIsCome(1);
                        userDayAttendance.setFiveStatus("正常");
                        userDayAttendance.setNormalNum(1 + userDayAttendance.getNormalNum());
                        userDayAttendance.setFirstEndTime(m.getDateTime());
                        flag = 1;
                        break;
                    }
                }
            }

            if (flag == 0) {
                //下班班异常处理
                userDayAttendance = this.outWork(userDayAttendance, l, map, date2);
                userDayAttendance.setFiveStatus("异常");
                userDayAttendance.setSecondEndTime(userDayAttendance.getSaveTime());
                if (userDayAttendance.getAbsenteeism() > 0) {
                    userDayAttendance.setAbsenteeism1(1);
                    userDayAttendance.setAbsenteeism(0);
                }
            }


            //一天打卡多次的 分4次 6次 8次
            if (type > 1) {
                flag = 0;
                for (MonthlyAttendanceIni m : l) {
                    //第二次上班正常打卡情况
                    if (AttendanceConstants.addressIn.indexOf(m.getAddress()) > -1) {
                        if (DateUtils.dateTime("yyyy-MM-dd HH:mm", m.getDateTime()).getTime() >= date3.getTime() - AttendanceConstants.beforeDateTime
                                && DateUtils.dateTime("yyyy-MM-dd HH:mm", m.getDateTime()).getTime() <= date3.getTime()) {
                            userDayAttendance.setIsAttendance(1);
                            userDayAttendance.setIsCome(1);
                            userDayAttendance.setNormalNum(1 + userDayAttendance.getNormalNum());
                            userDayAttendance.setSecondStatus("正常");
                            userDayAttendance.setSecondBeginTime(m.getDateTime());

                            flag = 1;
                            break;
                        }
                    }
                }
                if (flag == 0) {
                    //上班异常处理
                    userDayAttendance = this.inWork(userDayAttendance, l, map, date3);
                    userDayAttendance.setSecondStatus("异常");
                    userDayAttendance.setSecondBeginTime(userDayAttendance.getSaveTime());
                    if (userDayAttendance.getAbsenteeism() > 0) {
                        userDayAttendance.setAbsenteeism2(1);
                        userDayAttendance.setAbsenteeism(0);
                    }
                }


                flag = 0;
                //第二次下班打卡情况
                for (MonthlyAttendanceIni m : l) {
                    if (AttendanceConstants.addressOut.indexOf(m.getAddress()) != -1) {
                        if (DateUtils.dateTime("yyyy-MM-dd HH:mm", m.getDateTime()).getTime() >= date4.getTime()
                                && DateUtils.dateTime("yyyy-MM-dd HH:mm", m.getDateTime()).getTime() <= date4.getTime() + AttendanceConstants.afterDateTime
                        ) {
                            userDayAttendance.setIsAttendance(1);
                            userDayAttendance.setIsCome(1);
                            userDayAttendance.setNormalNum(1 + userDayAttendance.getNormalNum());
                            userDayAttendance.setSixStatus("正常");
                            userDayAttendance.setSecondEndTime(m.getDateTime());
                            flag = 1;
                            break;
                        }
                    }
                }

                if (flag == 0) {
                    //下班班异常处理
                    userDayAttendance = this.outWork(userDayAttendance, l, map, date4);
                    userDayAttendance.setSixStatus("异常");
                    userDayAttendance.setSecondEndTime(userDayAttendance.getSaveTime());
                    if (userDayAttendance.getAbsenteeism() > 0) {
                        userDayAttendance.setAbsenteeism2(1);
                        userDayAttendance.setAbsenteeism(0);
                    }
                }

            }


            //一天打卡多次的 分4次 6次 8次
            if (type > 2) {
                flag = 0;
                //第三次上班正常打卡情况
                for (MonthlyAttendanceIni m : l) {
                    if (AttendanceConstants.addressIn.indexOf(m.getAddress()) != -1) {
                        if (DateUtils.dateTime("yyyy-MM-dd HH:mm", m.getDateTime()).getTime() >= date5.getTime() - AttendanceConstants.beforeDateTime
                                && DateUtils.dateTime("yyyy-MM-dd HH:mm", m.getDateTime()).getTime() <= date5.getTime()) {
                            userDayAttendance.setIsAttendance(1);
                            userDayAttendance.setIsCome(1);
                            userDayAttendance.setNormalNum(1 + userDayAttendance.getNormalNum());
                            userDayAttendance.setThreeStatus("正常");
                            userDayAttendance.setThreeBeginTime(m.getDateTime());

                            flag = 1;
                            break;
                        }
                    }
                }
                if (flag == 0) {
                    //上班异常处理
                    userDayAttendance = this.inWork(userDayAttendance, l, map, date5);
                    userDayAttendance.setThreeStatus("异常");
                    userDayAttendance.setThreeBeginTime(userDayAttendance.getSaveTime());
                    if (userDayAttendance.getAbsenteeism() > 0) {
                        userDayAttendance.setAbsenteeism3(1);
                        userDayAttendance.setAbsenteeism(0);
                    }
                }


                flag = 0;
                //第三次下班打卡情况
                for (MonthlyAttendanceIni m : l) {
                    if (AttendanceConstants.addressOut.indexOf(m.getAddress()) != -1) {
                        if (DateUtils.dateTime("yyyy-MM-dd HH:mm", m.getDateTime()).getTime() >= date6.getTime()
                                && DateUtils.dateTime("yyyy-MM-dd HH:mm", m.getDateTime()).getTime() <= date6.getTime() + AttendanceConstants.afterDateTime
                        ) {
                            userDayAttendance.setIsAttendance(1);
                            userDayAttendance.setIsCome(1);
                            userDayAttendance.setNormalNum(1 + userDayAttendance.getNormalNum());
                            userDayAttendance.setSevenStatus("正常");
                            userDayAttendance.setThreeEndTime(m.getDateTime());
                            flag = 1;
                            break;
                        }
                    }
                }
                if (flag == 0) {
                    //下班班异常处理
                    userDayAttendance = this.outWork(userDayAttendance, l, map, date6);
                    userDayAttendance.setSevenStatus("异常");
                    userDayAttendance.setThreeEndTime(userDayAttendance.getSaveTime());
                    if (userDayAttendance.getAbsenteeism() > 0) {
                        userDayAttendance.setAbsenteeism3(1);
                        userDayAttendance.setAbsenteeism(0);
                    }
                }


            }

            //一天打卡多次的 分4次 6次 8次
            if (type > 3) {
                flag = 0;
                //第四次上班正常打卡情况
                for (MonthlyAttendanceIni m : l) {
                    if (AttendanceConstants.addressIn.indexOf(m.getAddress()) != -1) {
                        if (DateUtils.dateTime("yyyy-MM-dd HH:mm", m.getDateTime()).getTime() >= date7.getTime() - AttendanceConstants.beforeDateTime
                                && DateUtils.dateTime("yyyy-MM-dd HH:mm", m.getDateTime()).getTime() <= date7.getTime()) {
                            userDayAttendance.setIsAttendance(1);
                            userDayAttendance.setIsCome(1);
                            userDayAttendance.setNormalNum(1 + userDayAttendance.getNormalNum());
                            userDayAttendance.setFourStatus("正常");
                            userDayAttendance.setFourBeginTime(m.getDateTime());

                            flag = 1;
                            break;
                        }
                    }
                }
                if (flag == 0) {
                    //上班异常处理
                    userDayAttendance = this.inWork(userDayAttendance, l, map, date7);
                    userDayAttendance.setFourStatus("异常");
                    userDayAttendance.setThreeEndTime(userDayAttendance.getSaveTime());
                    if (userDayAttendance.getAbsenteeism() > 0) {
                        userDayAttendance.setAbsenteeism4(1);
                        userDayAttendance.setAbsenteeism(0);
                    }
                }


                flag = 0;
                //第四次下班打卡情况
                for (MonthlyAttendanceIni m : l) {
                    if (AttendanceConstants.addressOut.indexOf(m.getAddress()) != -1) {
                        if (DateUtils.dateTime("yyyy-MM-dd HH:mm", m.getDateTime()).getTime() >= date8.getTime()
                                && DateUtils.dateTime("yyyy-MM-dd HH:mm", m.getDateTime()).getTime() <= date8.getTime() + AttendanceConstants.afterDateTime
                        ) {
                            userDayAttendance.setIsAttendance(1);
                            userDayAttendance.setIsCome(1);
                            userDayAttendance.setNormalNum(1 + userDayAttendance.getNormalNum());
                            userDayAttendance.setEightStatus("正常");
                            userDayAttendance.setFourEndTime(m.getDateTime());
                            flag = 1;
                            break;
                        }
                    }
                }

                if (flag == 0) {
                    //下班班异常处理
                    userDayAttendance = this.outWork(userDayAttendance, l, map, date8);
                    userDayAttendance.setEightStatus("异常");
                    userDayAttendance.setFourEndTime(userDayAttendance.getSaveTime());
                    if (userDayAttendance.getAbsenteeism() > 0) {
                        userDayAttendance.setAbsenteeism4(1);
                        userDayAttendance.setAbsenteeism(0);
                    }
                }
            }
            userDayAttendance.setAbsenteeism(userDayAttendance.getAbsenteeism1() + userDayAttendance.getAbsenteeism2()
                    + userDayAttendance.getAbsenteeism3() + userDayAttendance.getAbsenteeism4());
            userDayAttendance.setAbnormalNum(userDayAttendance.getLate() + userDayAttendance.getGenerallyLate()
                    + userDayAttendance.getSeriouslyLate() + userDayAttendance.getLeaveEarly()
                    + userDayAttendance.getAbsenteeism());
            resultList.add(userDayAttendance);

        }


        List<Map<String, Object>> resultGroupList = new ArrayList<>();

        Set<String> groupSet = new HashSet<>();
        for (UserDayAttendance u : resultList) {
            groupSet.add(String.valueOf(u.getGroupId()));
        }

        for (Map<String, Object> m : groupList) {
            for (String s : groupSet) {
                if (Long.parseLong(s) == Long.parseLong(m.get("groupId").toString())) {
                    resultGroupList.add(m);
                }
            }
        }

        List<UserDayAttendanceSum> userDayAttendanceSumList = new ArrayList<>();
        // List<Map<String, Object>> restList = attendanceStatisticsService.listRestSchedule(fistRecordDateTime);

        for (Map<String, Object> m : resultGroupList) {
            List<UserDayAttendance> userDayAttendances = new ArrayList<>();
            UserDayAttendanceSum userDayAttendanceSum = new UserDayAttendanceSum();
            userDayAttendanceSum.setCreateBy(getUsername());
            userDayAttendanceSum.setDateTime(date);
            userDayAttendanceSum.setGroupId(Long.parseLong(m.get("groupId").toString()));
            userDayAttendanceSum.setGroupName(m.get("groupName").toString());
            for (UserDayAttendance u : resultList) {
                if (u.getGroupId() == Long.parseLong(m.get("groupId").toString())) {
                    //计算汇总值
                    int num = 0;
                    if (u.getLate() > 0) {
                        userDayAttendanceSum.setLate(1 + userDayAttendanceSum.getLate());
                        num = 1;
                    }
                    if (u.getGenerallyLate() > 0) {
                        userDayAttendanceSum.setGenerallyLate(1 + userDayAttendanceSum.getGenerallyLate());
                        num = 1;
                    }
                    if (u.getSeriouslyLate() > 0) {
                        userDayAttendanceSum.setSeriouslyLate(1 + userDayAttendanceSum.getSeriouslyLate());
                        num = 1;
                    }
                    if (u.getLeaveEarly() > 0) {
                        userDayAttendanceSum.setLeaveEarly(1 + userDayAttendanceSum.getLeaveEarly());
                        num = 1;
                    }

                    if (u.getAbsenteeism() > 0) {
                        userDayAttendanceSum.setAbsenteeism(userDayAttendanceSum.getAbsenteeism() + 1);
                        num = 1;
                    }
                    userDayAttendanceSum.setAbnormalAttendance(userDayAttendanceSum.getAbnormalAttendance() + num);
                    userDayAttendances.add(u);
                }
            }

            for (List<UserDayAttendance> l : groupOfList) {
                for (UserDayAttendance u : l) {
                    if (u.getGroupId() == Long.parseLong(m.get("groupId").toString())) {
                        userDayAttendanceSum.setMustAttendance(l.size());
                        break;
                    }
                }

            }

            for (Map<String, Object> map : restList) {
                for (Map.Entry<String, Object> stringObjectEntry : map.entrySet()) {
                    if (stringObjectEntry.getKey().toString().equals(m.get("groupId").toString())) {
                        userDayAttendanceSum.setRestAttendance(userDayAttendanceSum.getRestAttendance() + 1);
                    }
                }
            }
            int size =0;
            for (int i = 0; i < userScheduleList.size(); i++) {
                Map<String, Object> map = userScheduleList.get(i);
                if (Long.parseLong(map.get("groupId").toString()) == Long.parseLong(m.get("groupId").toString())) {
                    size++;
                }
            }
            int normalAttendanceNum =0;
            for (int i = 0; i < collectList.size(); i++) {
                Map<String, Object> map = collectList.get(i);
                if (Long.parseLong(map.get("groupId").toString()) == Long.parseLong(m.get("groupId").toString())) {
                    normalAttendanceNum++;
                }
            }
            userDayAttendanceSum.setMustAttendance(size-userDayAttendanceSum.getRestAttendance());
            userDayAttendanceSum.setNormalAttendance(normalAttendanceNum- userDayAttendanceSum.getRestAttendance() );
            userDayAttendanceSum.setUserDayAttendanceList(userDayAttendances);
            userDayAttendanceSumList.add(userDayAttendanceSum);
        }

        resultMap.put("dateTime", fistRecordDateTime);
        resultMap.put("userDayAttendanceSumList", userDayAttendanceSumList);
        attendanceStatisticsService.addUserDayAttendanceSum(resultMap);
        return AjaxResult.success("成功");
    }

    //上班异常
    private UserDayAttendance inWork(UserDayAttendance userDayAttendance, List<MonthlyAttendanceIni> l, Map<String, Object> map, Date date) {
        long late = Integer.parseInt(map.get("late").toString()) * 60 * 1000;
        long generallyLate = Integer.parseInt(map.get("generallyLate").toString()) * 60 * 1000;
        long seriouslyLate = Integer.parseInt(map.get("seriouslyLate").toString()) * 60 * 1000;

        long absenteeism = Integer.parseInt(map.get("absenteeism").toString()) * 60 * 1000;
        for (MonthlyAttendanceIni m : l) {
            //上班
            //迟到

            if (AttendanceConstants.addressIn.indexOf(m.getAddress()) != -1) {

            if (DateUtils.dateTime("yyyy-MM-dd HH:mm", m.getDateTime()).getTime() > date.getTime()
                    && DateUtils.dateTime("yyyy-MM-dd HH:mm", m.getDateTime()).getTime() <= date.getTime() + late) {

                userDayAttendance.setLate(1 + userDayAttendance.getLate());
                userDayAttendance.setIsAbnormal(1);
                userDayAttendance.setSaveTime(m.getDateTime());
                return userDayAttendance;


            } else if (DateUtils.dateTime("yyyy-MM-dd HH:mm", m.getDateTime()).getTime() > date.getTime()
                    && DateUtils.dateTime("yyyy-MM-dd HH:mm", m.getDateTime()).getTime() <= date.getTime() + generallyLate) {

                userDayAttendance.setGenerallyLate(1 + userDayAttendance.getGenerallyLate());
                userDayAttendance.setIsAbnormal(1);
                userDayAttendance.setSaveTime(m.getDateTime());
                return userDayAttendance;

            } else if (DateUtils.dateTime("yyyy-MM-dd HH:mm", m.getDateTime()).getTime() > date.getTime()
                    && DateUtils.dateTime("yyyy-MM-dd HH:mm", m.getDateTime()).getTime() <= date.getTime() + seriouslyLate) {
                userDayAttendance.setSeriouslyLate(1 + userDayAttendance.getSeriouslyLate());
                userDayAttendance.setIsAbnormal(1);
                userDayAttendance.setSaveTime(m.getDateTime());
                return userDayAttendance;

            } else if (DateUtils.dateTime("yyyy-MM-dd HH:mm", m.getDateTime()).getTime() > date.getTime()
                    && DateUtils.dateTime("yyyy-MM-dd HH:mm", m.getDateTime()).getTime() <= date.getTime() + absenteeism) {
                userDayAttendance.setAbsenteeism(1);
                userDayAttendance.setIsAbnormal(1);
                userDayAttendance.setSaveTime(m.getDateTime());
                return userDayAttendance;

            }
        }
        }

        userDayAttendance.setAbsenteeism(1);
        userDayAttendance.setIsAbnormal(1);
        return userDayAttendance;


    }

    //下班班异常
    private UserDayAttendance outWork(UserDayAttendance userDayAttendance, List<MonthlyAttendanceIni> l, Map<String, Object> map, Date date) {

        long leaveEarly = Integer.parseInt(map.get("leaveEarly").toString()) * 60 * 1000;
        long absenteeism = Integer.parseInt(map.get("absenteeism").toString()) * 60 * 1000;


        for (MonthlyAttendanceIni m : l) {
            if (AttendanceConstants.addressOut.indexOf(m.getAddress()) != -1) {
                //下班早退
            if (DateUtils.dateTime("yyyy-MM-dd HH:mm", m.getDateTime()).getTime() < date.getTime()
                    && DateUtils.dateTime("yyyy-MM-dd HH:mm", m.getDateTime()).getTime() >= date.getTime() - leaveEarly) {

                userDayAttendance.setLeaveEarly(1 + userDayAttendance.getLeaveEarly());
                userDayAttendance.setIsAbnormal(1);
                userDayAttendance.setSaveTime(m.getDateTime());
                return userDayAttendance;


            }  //下班旷工
            else if (DateUtils.dateTime("yyyy-MM-dd HH:mm", m.getDateTime()).getTime() < date.getTime() - leaveEarly
                    && DateUtils.dateTime("yyyy-MM-dd HH:mm", m.getDateTime()).getTime() >= date.getTime() - absenteeism) {

                userDayAttendance.setAbsenteeism(1);
                userDayAttendance.setIsAbnormal(1);
                userDayAttendance.setSaveTime(m.getDateTime());
                return userDayAttendance;

            }
        }
        }

        userDayAttendance.setAbsenteeism(1);
        userDayAttendance.setIsAbnormal(1);
        return userDayAttendance;


    }


    private <T> List<T> baseImport(InputStream inputStream, Integer titleRows, Integer headerRows,
                                   boolean needVerify, Class<T> pojoClass) throws Exception {
        if (inputStream == null) {
            return null;
        } else {
            final ImportParams params = new ImportParams();
            params.setTitleRows(titleRows);
            params.setHeadRows(headerRows);
            params.setNeedVerify(true);
            params.setNeedSave(false);
            return ExcelImportUtil.importExcel(inputStream, pojoClass, params);
        }

    }


}
